package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.vo.hosp.DepartmentQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;


    @Override
    public void save(Map<String, Object> paramMap) {

        //把参数map集合转换对象 Department
        String mapString = JSONObject.toJSONString(paramMap);//map转字符串
        Department department = JSONObject.parseObject(mapString, Department.class);//字符串转对象
        Department departmentExist = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getDepcode(), department.getHoscode());

        System.out.println("departmentExist?"+departmentExist);
        //判断是否存在数据
        if (departmentExist != null) {
            departmentExist.setUpdateTime(new Date());
            departmentExist.setIsDeleted(0);
            //存在数据，更新
            departmentRepository.save(departmentExist);
        } else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            //不存在数据，插入
            departmentRepository.save(department);
        }

    }

    @Override
    public Page<Department> selectPage(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        //创建Pageable对象 设置页码和每页显示条数
        Pageable pageable = (Pageable) PageRequest.of(page - 1, limit);
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);
        //创建Example对象
        ExampleMatcher matcher = ExampleMatcher.matching().
                withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        Example<Department> example = Example.of(department, matcher);

        Page<Department> all = departmentRepository.findAll(example, pageable);

        return all;
    }

    /**
     * 科室删除
     *
     * @param hoscode
     * @param depcode
     */
    @Override
    public void remove(String hoscode, String depcode) {
        //根据hoscode和depcode查询数据
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(depcode, hoscode);

        System.out.println("department内容"+department);
        //判断是否存在数据
        if (department != null) {
            //删除数据
            departmentRepository.deleteById(department.getId());
        }
    }
}
